// 全局变量定义
// 动态构建API URL，使用当前页面的主机和端口
const API_URL = `http://${window.location.hostname}:${window.location.port}`;

document.addEventListener('DOMContentLoaded', function() {
    // 初始化变量
    let darkMode = false;

    // 获取DOM元素
    const questionInput = document.getElementById('question-input');
    const submitQuestion = document.getElementById('submit-question');
    const chatContainer = document.getElementById('chat-container');
    const documentsContainer = document.getElementById('documents-container');
    const statusIndicator = document.getElementById('status-indicator');
    const themeToggle = document.getElementById('theme-toggle');
    const uploadArea = document.getElementById('upload-area');
    const fileUpload = document.getElementById('file-upload');
    const uploadStatus = document.getElementById('upload-status');

    // 检查API服务状态
    checkApiStatus();
    setInterval(checkApiStatus, 5000);

    // 主题切换
    themeToggle.addEventListener('click', function() {
        darkMode = !darkMode;
        if (darkMode) {
            document.body.classList.add('bg-gray-900', 'text-white');
            document.querySelectorAll('.bg-white').forEach(el => {
                el.classList.remove('bg-white');
                el.classList.add('bg-gray-800');
            });
            document.querySelectorAll('.bg-gray-50').forEach(el => {
                el.classList.remove('bg-gray-50');
                el.classList.add('bg-gray-700');
            });
            document.querySelectorAll('.text-gray-500').forEach(el => {
                el.classList.remove('text-gray-500');
                el.classList.add('text-gray-300');
            });
            themeToggle.innerHTML = '<i class="fa fa-sun-o"></i>';
        } else {
            document.body.classList.remove('bg-gray-900', 'text-white');
            document.querySelectorAll('.bg-gray-800').forEach(el => {
                el.classList.remove('bg-gray-800');
                el.classList.add('bg-white');
            });
            document.querySelectorAll('.bg-gray-700').forEach(el => {
                el.classList.remove('bg-gray-700');
                el.classList.add('bg-gray-50');
            });
            document.querySelectorAll('.text-gray-300').forEach(el => {
                el.classList.remove('text-gray-300');
                el.classList.add('text-gray-500');
            });
            themeToggle.innerHTML = '<i class="fa fa-moon-o"></i>';
        }
    });

    // 提交问题
    submitQuestion.addEventListener('click', submitQuery);
    questionInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            submitQuery();
        }
    });

    // 文件上传处理
    uploadArea.addEventListener('click', function() {
        fileUpload.click();
    });

    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('border-blue-500', 'bg-blue-50');
    });

    uploadArea.addEventListener('dragleave', function() {
        uploadArea.classList.remove('border-blue-500', 'bg-blue-50');
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('border-blue-500', 'bg-blue-50');
        if (e.dataTransfer.files.length) {
            handleFileUpload(e.dataTransfer.files[0]);
        }
    });

    fileUpload.addEventListener('change', function() {
        if (this.files.length) {
            handleFileUpload(this.files[0]);
        }
    });

    // 函数：提交查询
    function submitQuery() {
        const question = questionInput.value.trim();
        if (!question) return;

        // 添加用户问题到聊天历史
        addMessage('user', question);
        questionInput.value = '';

        // 显示加载状态
        addMessage('loading', '');

        // 获取token - 同时检查'token'和'access_token'键
        let token = localStorage.getItem('access_token') || localStorage.getItem('token') || 
                    sessionStorage.getItem('access_token') || sessionStorage.getItem('token');
        console.log('localStorage中的access_token:', localStorage.getItem('access_token'));
        console.log('localStorage中的token:', localStorage.getItem('token'));
        console.log('sessionStorage中的access_token:', sessionStorage.getItem('access_token'));
        console.log('sessionStorage中的token:', sessionStorage.getItem('token'));
        
        if (!token) {
            token = getCookie('access_token') || getCookie('token');
            console.log('Cookie中的access_token:', getCookie('access_token'));
            console.log('Cookie中的token:', getCookie('token'));
        }
        console.log('查询使用的token:', token);
        console.log('当前Cookie:', document.cookie);

        // 创建请求头
        const headers = {
            'Content-Type': 'application/json'
        };
        // 如果token存在，添加到请求头
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
            console.log('已添加Authorization头:', headers['Authorization']);
            // 检查token格式是否正确
            if (token.split('.').length !== 3) {
                console.warn('token格式不正确，可能无效');
            }
        } else {
            console.warn('查询未找到有效的token');
        }
        console.log('完整请求头:', JSON.stringify(headers));

        // 调用API，包含credentials以传递Cookie
        fetch(`${API_URL}/rag-query`, {
            method: 'POST',
            headers: headers,
            credentials: 'include', // 包含Cookie
            body: JSON.stringify({ query: question })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`API响应错误: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // 移除加载状态
            const loadingElement = chatContainer.querySelector('.loading-message');
            if (loadingElement) {
                loadingElement.remove();
            }

            // 添加助手回答和引用
            addMessage('assistant', data.answer, data.references);

            // 不再需要单独检索文档，因为引用信息已经随查询结果返回
            // 清空文档容器
        documentsContainer.innerHTML = '';

        if (data.references && data.references.length) {
            // 显示引用文档（去重处理）
            // 使用Set去重，基于source和id
            const uniqueReferences = [];
            const seenReferences = new Set();

            data.references.forEach(ref => {
                // 创建一个唯一标识符，仅基于source
                const refKey = ref.source;
                if (!seenReferences.has(refKey)) {
                    seenReferences.add(refKey);
                    uniqueReferences.push(ref);
                }
            });

            if (uniqueReferences.length) {
                uniqueReferences.forEach((ref, index) => {
                    addReference(ref, index + 1);
                });
            } else {
                documentsContainer.innerHTML = `
                    <div class="text-center text-gray-500 py-4">
                        <i class="fa fa-exclamation-circle text-xl mb-2"></i>
                        <p>未找到相关文档</p>
                    </div>
                `;
            }
        } else {
            // 没有找到相关文档
            documentsContainer.innerHTML = `
                <div class="text-center text-gray-500 py-4">
                    <i class="fa fa-exclamation-circle text-xl mb-2"></i>
                    <p>未找到相关文档</p>
                </div>
            `;
        }
            // 旧的检索相关文档代码已移除，引用信息已随查询结果返回
            // fetch(`${API_URL}/process-text`, {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify({ text: question, metadata: { type: 'query' } })
            // })
            // .then(res => res.json())
            // .then(docData => {
            //     // 清空文档容器
            //     documentsContainer.innerHTML = '';

            //     if (docData && docData.relevant_documents && docData.relevant_documents.length) {
            //         // 显示相关文档
            //         docData.relevant_documents.forEach((doc, index) => {
            //             addDocument(doc, index + 1);
            //         });
            //     } else {
            //         // 没有找到相关文档
            //         documentsContainer.innerHTML = `
            //             <div class="text-center text-gray-500 py-4">
            //                 <i class="fa fa-exclamation-circle text-xl mb-2"></i>
            //                 <p>未找到相关文档</p>
            //             </div>
            //         `;
            //     }
            // })
            // .catch(error => {
            //     console.error('获取相关文档失败:', error);
            //     documentsContainer.innerHTML = `
            //         <div class="text-center text-red-500 py-4">
            //             <i class="fa fa-times-circle text-xl mb-2"></i>
            //             <p>获取相关文档失败</p>
            //         </div>
            //     `;
            // });
        })
        .catch(error => {
            console.error('查询失败:', error);
            // 移除加载状态
            const loadingElement = chatContainer.querySelector('.loading-message');
            if (loadingElement) {
                loadingElement.remove();
            }
            // 添加错误消息
            addMessage('error', '查询失败，请稍后重试');
        });
    }

    // 函数：添加消息到聊天历史
    function addMessage(type, content, references = []) {
        const messageDiv = document.createElement('div');

        if (type === 'user') {
            messageDiv.className = 'mb-4 flex items-start justify-end';
            messageDiv.innerHTML = `
                <div class="bg-blue-600 text-white rounded-lg rounded-tl-none p-3 max-w-[80%]">
                    <p>${content}</p>
                </div>
                <div class="ml-2 w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold">
                    <i class="fa fa-user"></i>
                </div>
            `;
        } else if (type === 'assistant') {
            messageDiv.className = 'mb-4 flex items-start';
            messageDiv.innerHTML = `
                <div class="mr-2 w-8 h-8 bg-gray-500 rounded-full flex items-center justify-center text-white font-bold">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-gray-100 text-gray-800 rounded-lg rounded-tr-none p-3 max-w-[80%]">
                    <p>${content}</p>
                    ${references.length ? `
                    <div class="mt-2 pt-2 border-t border-gray-200 text-sm text-gray-600">
                        <p class="font-medium mb-1">参考来源:</p>
                        <ul class="list-disc list-inside">
                            ${(() => {
                                // 对引用进行去重，基于source
                                const uniqueReferences = [];
                                const seenSources = new Set();
                                references.forEach(ref => {
                                    if (!seenSources.has(ref.source)) {
                                        seenSources.add(ref.source);
                                        uniqueReferences.push(ref);
                                    }
                                });
                                return uniqueReferences.map(ref => `<li><a href="#reference-${ref.id}" class="text-blue-500 hover:underline">${ref.source}</a></li>`).join('');
                            })()}
                        </ul>
                    </div>
                    ` : ''}
                </div>
            `;
        } else if (type === 'loading') {
            messageDiv.className = 'mb-4 flex items-start loading-message';
            messageDiv.innerHTML = `
                <div class="mr-2 w-8 h-8 bg-gray-500 rounded-full flex items-center justify-center text-white font-bold">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-gray-100 text-gray-800 rounded-lg rounded-tr-none p-3 max-w-[80%]">
                    <div class="flex items-center space-x-1">
                        <div class="w-2 h-2 bg-blue-500 rounded-full loader animate-pulse"></div>
                        <div class="w-2 h-2 bg-blue-500 rounded-full loader animate-pulse delay-75"></div>
                        <div class="w-2 h-2 bg-blue-500 rounded-full loader animate-pulse delay-150"></div>
                    </div>
                </div>
            `;
        } else if (type === 'error') {
            messageDiv.className = 'mb-4 flex items-start';
            messageDiv.innerHTML = `
                <div class="mr-2 w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white font-bold">
                    <i class="fa fa-exclamation-triangle"></i>
                </div>
                <div class="bg-red-100 text-red-800 rounded-lg rounded-tr-none p-3 max-w-[80%]">
                    <p>${content}</p>
                </div>
            `;
        }

        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 函数：添加引用文档到容器
    function addReference(ref, index) {
        const refDiv = document.createElement('div');
        refDiv.id = `reference-${ref.id}`;
        refDiv.className = 'mb-4 p-3 bg-white rounded-lg shadow-sm border border-gray-200';

        refDiv.innerHTML = `
            <div class="flex justify-between items-start mb-2">
                <h3 class="font-semibold text-blue-600">参考来源 ${index}: ${ref.source}</h3>
            </div>
            <p class="text-sm text-gray-700 mb-2">${ref.preview}</p>
            <div class="text-xs text-gray-500 flex justify-between">
                <button class="text-blue-500 hover:text-blue-700 view-full-reference" data-ref-id="${ref.id}">查看完整内容</button>
            </div>
        `;

        documentsContainer.appendChild(refDiv);

        // 添加查看完整内容的事件监听
        refDiv.querySelector('.view-full-reference').addEventListener('click', function() {
            alert(`参考来源 ${index} 完整内容:\n\n${ref.full_text}`);
        });
    }

    // 函数：添加文档到文档容器
    function addDocument(doc, index) {
        const docDiv = document.createElement('div');
        docDiv.className = 'mb-4 p-3 bg-white rounded-lg shadow-sm border border-gray-200';

        // 截断过长的文档内容
        let truncatedContent = doc.text;
        if (truncatedContent.length > 200) {
            truncatedContent = truncatedContent.substring(0, 200) + '...';
        }

        docDiv.innerHTML = `
            <div class="flex justify-between items-start mb-2">
                <h3 class="font-semibold text-blue-600">文档 ${index}</h3>
                ${doc.metadata && doc.metadata.title ? `<span class="text-sm text-gray-500">${doc.metadata.title}</span>` : ''}
            </div>
            <p class="text-sm text-gray-700 mb-2">${truncatedContent}</p>
            <div class="text-xs text-gray-500 flex justify-between">
                ${doc.metadata && doc.metadata.category ? `<span>类别: ${doc.metadata.category}</span>` : ''}
                <button class="text-blue-500 hover:text-blue-700 view-full-doc" data-doc-index="${index}">查看完整文档</button>
            </div>
        `;

        documentsContainer.appendChild(docDiv);

        // 添加查看完整文档的事件监听
        docDiv.querySelector('.view-full-doc').addEventListener('click', function() {
            alert(`文档 ${index} 完整内容:\n\n${doc.text}`);
        });
    }

    // 函数：处理文件上传
function handleFileUpload(file) {
    // 检查文件类型
    const fileExtension = file.name.split('.').pop().toLowerCase();
    if (!['txt', 'pdf', 'docx'].includes(fileExtension)) {
        showUploadStatus('仅支持TXT、PDF和Word格式文件', 'error');
        return;
    }

    showUploadStatus('正在上传...', 'info');

    // 获取token
    let token = localStorage.getItem('access_token') || sessionStorage.getItem('access_token');
    if (!token) {
        token = getCookie('access_token');
    }
    console.log('上传文档使用的token:', token);

    // 创建请求头
    const headers = {}
    // 如果token存在，添加到请求头
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
        console.log('已添加Authorization头:', headers['Authorization']);
    } else {
        console.warn('上传文档未找到有效的token');
    }

    const formData = new FormData();
    formData.append('file', file);

    console.log('开始上传文件:', file.name);
    console.log('上传URL:', `${API_URL}/upload-document/`);
    
    fetch(`${API_URL}/upload-document/`, {
            method: 'POST',
            headers: headers,
            credentials: 'include',
            body: formData
        })
        .then(response => {
            console.log('上传响应状态:', response.status, response.statusText);
            console.log('上传响应头:', response.headers);
            
            if (!response.ok) {
                // 对于错误响应，也尝试获取文本内容以获取详细错误信息
                return response.text().then(errorText => {
                    let errorMessage = `服务器响应错误: ${response.status} ${response.statusText}`;
                    try {
                        // 尝试解析错误响应中的JSON
                        const errorData = JSON.parse(errorText);
                        if (errorData.detail) {
                            errorMessage += `. 错误详情: ${errorData.detail}`;
                        }
                    } catch (jsonError) {
                        // 如果解析失败，使用原始错误文本
                        errorMessage += `. 错误详情: ${errorText}`;
                    }
                    throw new Error(errorMessage);
                });
            }
            return response.text(); // 先以文本形式获取响应
        })
        .then(text => {
            console.log('上传响应文本:', text);
            
            try {
                // 尝试解析JSON
                const data = JSON.parse(text);
                return data;
            } catch (error) {
                // 如果解析失败，抛出更友好的错误
                throw new Error(`服务器返回的响应格式无效: ${error.message}。请联系管理员检查服务器日志获取详细信息。`);
            }
        })
        .then(data => {
            console.log('文件上传成功:', data);
            
            // 使用客户端文件名，避免依赖服务器返回的filename
            showUploadStatus(`文件上传成功: ${file.name}`, 'success');
            
            // 显示文档信息
            if (data.metadata) {
                showDocumentInfo(file.name, fileExtension.toUpperCase(), data.metadata);
            }
            
            // 延迟3秒后隐藏上传状态
            setTimeout(() => {
                uploadStatus.classList.add('hidden');
            }, 3000);
        })
        .catch(error => {
            console.error('文件上传失败:', error);
            console.error('错误堆栈:', error.stack);
            // 显示更友好的错误消息
            let displayMessage = '文件上传失败: ';
            if (error.message.includes('服务器响应错误: 500')) {
                displayMessage += '服务器内部错误，请联系管理员并提供上传文件信息。';
            } else if (error.message.includes('响应不是有效的JSON')) {
                displayMessage += '服务器返回格式错误，请联系管理员。';
            } else {
                displayMessage += error.message;
            }
            showUploadStatus(displayMessage, 'error');
            // 记录详细错误信息到本地存储，供开发人员查看
            try {
                const errorLog = {
                    timestamp: new Date().toISOString(),
                    errorMessage: error.message,
                    errorStack: error.stack,
                    fileName: file.name,
                    fileSize: file.size,
                    fileType: file.type
                };
                localStorage.setItem('lastUploadError', JSON.stringify(errorLog));
                console.log('错误信息已保存到本地存储');
            } catch (e) {
                console.error('保存错误信息到本地存储失败:', e);
            }
        });
    }

    // 函数：显示上传状态
    function showUploadStatus(message, type) {
        uploadStatus.textContent = message;
        uploadStatus.classList.remove('hidden', 'text-green-600', 'text-red-600', 'text-blue-600');

        if (type === 'success') {
            uploadStatus.classList.add('text-green-600');
        } else if (type === 'error') {
            uploadStatus.classList.add('text-red-600');
        } else if (type === 'info') {
            uploadStatus.classList.add('text-blue-600');
        }
    }

    // 显示文档信息
function showDocumentInfo(fileName, fileType, metadata) {
    // 确保document-info容器存在
    let docInfoContainer = document.getElementById('document-info');
    if (!docInfoContainer) {
        // 如果不存在，创建一个
        docInfoContainer = document.createElement('div');
        docInfoContainer.id = 'document-info';
        docInfoContainer.className = 'mt-6';
        // 插入到上传区域下方
        uploadArea.parentNode.insertBefore(docInfoContainer, uploadArea.nextSibling);
    }

    docInfoContainer.innerHTML = `
        <div class="p-4 bg-gray-50 rounded-lg border border-gray-200 dark:bg-gray-800 dark:border-gray-700">
            <h4 class="font-semibold text-gray-800 dark:text-gray-200 mb-2">文档信息</h4>
            <p><span class="text-gray-600 dark:text-gray-400">文件名:</span> ${fileName}</p>
            <p><span class="text-gray-600 dark:text-gray-400">文件类型:</span> ${fileType}</p>
        </div>
    `;

    // 添加元数据信息
    if (metadata && Object.keys(metadata).length > 0) {
        const docInfoDiv = docInfoContainer.querySelector('div');
        const metadataElement = document.createElement('div');
        metadataElement.className = 'mt-2';
        metadataElement.innerHTML = '<p class="text-gray-600 dark:text-gray-400 font-medium">元数据:</p>';

        const metadataList = document.createElement('ul');
        metadataList.className = 'list-disc list-inside text-sm text-gray-700 dark:text-gray-300';

        for (const [key, value] of Object.entries(metadata)) {
            if (value) {  // 只显示有值的元数据
                const listItem = document.createElement('li');
                listItem.textContent = `${key}: ${value}`;
                metadataList.appendChild(listItem);
            }
        }

        metadataElement.appendChild(metadataList);
        docInfoDiv.appendChild(metadataElement);
    }

    docInfoContainer.classList.remove('hidden');
}

// 函数：检查API状态
function checkApiStatus() {
    fetch(`${API_URL}/`)
            .then(response => {
                if (response.ok) {
                    statusIndicator.innerHTML = '<i class="fa fa-circle text-green-300 mr-1"></i>服务运行中';
                } else {
                    statusIndicator.innerHTML = '<i class="fa fa-circle text-yellow-300 mr-1"></i>服务响应异常';
                }
            })
            .catch(error => {
                console.error('检查API状态失败:', error);
                statusIndicator.innerHTML = '<i class="fa fa-circle text-red-300 mr-1"></i>服务不可用';
            });
    }
});

// 知识库管理功能

// 初始化知识库管理
function initKnowledgeBaseManagement() {
    const refreshButton = document.getElementById('refresh-documents');
    const knowledgeBaseContainer = document.getElementById('knowledge-base-container');

    if (refreshButton && knowledgeBaseContainer) {
        // 添加刷新按钮点击事件
        refreshButton.addEventListener('click', function() {
            loadDocuments();
        });
        // 初始加载文档列表
        loadDocuments();
    }
}

// 加载文档列表
function loadDocuments() {
    const knowledgeBaseContainer = document.getElementById('knowledge-base-container');

    // 显示加载状态
    knowledgeBaseContainer.innerHTML = `
        <div class="text-center text-gray-500 py-8">
            <div class="inline-block w-6 h-6 border-2 border-gray-400 border-t-blue-500 rounded-full loader"></div>
            <p class="mt-2">加载文档列表中...</p>
        </div>
    `;

    // 调用API获取文档列表
    // 重点获取access_token（后端返回的token名称）
    let token = localStorage.getItem('access_token') || sessionStorage.getItem('access_token');
    
    // 尝试从Cookie中获取access_token
    if (!token) {
        token = getCookie('access_token');
    }
    
    // 输出详细调试信息
    console.log('localStorage中的access_token:', localStorage.getItem('access_token'));
    console.log('sessionStorage中的access_token:', sessionStorage.getItem('access_token'));
    console.log('Cookie中的access_token:', getCookie('access_token'));
    console.log('最终获取到的token:', token);
    console.log('当前Cookie:', document.cookie);
    
    // 创建请求头
    const headers = {
        'Content-Type': 'application/json'
    };
    
    // 如果token存在，添加到请求头
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
        console.log('已添加Authorization头:', headers['Authorization']);
    } else {
        console.warn('未找到有效的token');
    }
    
// 全局辅助函数：从Cookie中获取值
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
}
    
    fetch(`${API_URL}/documents`, {
        method: 'GET',
        credentials: 'include',
        headers: headers
    })
    .then(response => {
        if (!response.ok) {
            if (response.status === 401) {
                throw new Error(`API响应错误: ${response.status}。请先登录系统。`);
            } else {
                throw new Error(`API响应错误: ${response.status}`);
            }
        }
        return response.json();
    })
    .then(data => {
        if (data.documents && data.documents.length > 0) {
            // 显示文档列表
            knowledgeBaseContainer.innerHTML = `
                <div class="text-sm font-medium text-gray-700 mb-2 pb-1 border-b border-gray-200">
                    <div class="flex justify-between">
                        <span>文档名称</span>
                        <span>操作</span>
                    </div>
                </div>
            `;

            data.documents.forEach(doc => {
                const docItem = document.createElement('div');
                docItem.className = 'flex justify-between items-center p-2 hover:bg-gray-100 rounded-md mb-1';
                docItem.innerHTML = `
                    <div class="flex items-center">
                        <i class="fa fa-file-text-o text-blue-500 mr-2"></i>
                        <span>${doc.source}</span>
                        <span class="ml-2 text-xs text-gray-500">(${doc.chunk_count}个块)</span>
                    </div>
                    <button class="delete-document text-red-500 hover:text-red-700 p-1" data-source="${encodeURIComponent(doc.source)}">
                        <i class="fa fa-trash-o"></i>
                    </button>
                `;

                knowledgeBaseContainer.appendChild(docItem);

                // 添加删除按钮事件监听
                docItem.querySelector('.delete-document').addEventListener('click', function() {
                    const source = decodeURIComponent(this.getAttribute('data-source'));
                    if (confirm(`确定要删除文档 "${source}" 吗？`)) {
                        deleteDocument(source);
                    }
                });
            });
        } else {
            // 没有文档
            knowledgeBaseContainer.innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa fa-folder-open-o text-xl mb-2"></i>
                    <p>暂无文档</p>
                </div>
            `;
        }
    })
    .catch(error => {
        console.error('加载文档列表失败:', error);
        // 检查是否为401未授权错误
        const isUnauthorized = error.message && error.message.includes('401');
        
        if (isUnauthorized) {
            knowledgeBaseContainer.innerHTML = `
                <div class="text-center text-red-500 py-8">
                    <i class="fa fa-lock text-xl mb-2"></i>
                    <p>请先登录系统</p>
                    <button id="go-to-login" class="mt-2 px-3 py-1 bg-blue-500 text-white rounded-md text-sm hover:bg-blue-600">
                        前往登录
                    </button>
                </div>
            `;
            
            // 添加前往登录按钮事件监听
            // 确保元素存在再添加事件监听
            const loginBtn = document.getElementById('go-to-login');
            if (loginBtn) {
                loginBtn.addEventListener('click', function() {
                    // 检查登录页面是否存在，使用正确的路径
                    window.location.href = '/static/auth_test.html';
                });
            }
        } else {
            knowledgeBaseContainer.innerHTML = `
                <div class="text-center text-red-500 py-8">
                    <i class="fa fa-times-circle text-xl mb-2"></i>
                    <p>加载文档列表失败</p>
                    <button id="retry-load-docs" class="mt-2 px-3 py-1 bg-blue-500 text-white rounded-md text-sm hover:bg-blue-600">
                        重试
                    </button>
                </div>
            `;

            // 仅在非401错误时添加重试按钮事件监听
            document.getElementById('retry-load-docs').addEventListener('click', function() {
                loadDocuments();
            });
        }
    });
}

// 自定义确认弹窗元素
let customConfirmModal = null;

// 初始化自定义弹窗
function initCustomConfirmModal() {
    if (customConfirmModal) return;

    customConfirmModal = document.createElement('div');
    customConfirmModal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden';
    customConfirmModal.innerHTML = `
        <div class="bg-white rounded-lg p-6 max-w-md w-full dark:bg-gray-800">
            <div class="text-center">
                <p id="confirm-message" class="text-gray-700 dark:text-gray-300 mb-4"></p>
                <div class="flex justify-center gap-3 mt-4">
                    <button id="confirm-yes" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
                        确定
                    </button>
                    <button id="confirm-no" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 dark:bg-gray-600 dark:text-gray-300">
                        取消
                    </button>
                </div>
            </div>
        </div>
    `;
    document.body.appendChild(customConfirmModal);
}

// 显示自定义确认弹窗
function showCustomConfirm(message) {
    return new Promise((resolve) => {
        initCustomConfirmModal();
        document.getElementById('confirm-message').textContent = message;
        customConfirmModal.classList.remove('hidden');

        const yesBtn = document.getElementById('confirm-yes');
        const noBtn = document.getElementById('confirm-no');

        const handleYes = () => {
            customConfirmModal.classList.add('hidden');
            yesBtn.removeEventListener('click', handleYes);
            noBtn.removeEventListener('click', handleNo);
            resolve(true);
        };

        const handleNo = () => {
            customConfirmModal.classList.add('hidden');
            yesBtn.removeEventListener('click', handleYes);
            noBtn.removeEventListener('click', handleNo);
            resolve(false);
        };

        yesBtn.addEventListener('click', handleYes);
        noBtn.addEventListener('click', handleNo);
    });
}

// 删除文档
async function deleteDocument(source) {
    // 显示自定义确认弹窗
    const confirmDelete = await showCustomConfirm('确定要删除文档 "' + source + '" 吗？');
    if (!confirmDelete) {
        return; // 用户取消删除
    }

    const knowledgeBaseContainer = document.getElementById('knowledge-base-container');

    // 显示加载状态
    const loadingElement = document.createElement('div');
    loadingElement.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    loadingElement.innerHTML = `
        <div class="bg-white rounded-lg p-6 max-w-md w-full dark:bg-gray-800">
            <div class="text-center">
                <div class="inline-block w-10 h-10 border-2 border-gray-400 border-t-blue-500 rounded-full loader mb-4"></div>
                <p class="text-gray-700 dark:text-gray-300">正在删除文档...</p>
            </div>
        </div>
    `;
    document.body.appendChild(loadingElement);

    // 调用API删除文档
    // 获取token
    let token = localStorage.getItem('access_token') || sessionStorage.getItem('access_token');
    if (!token) {
        token = getCookie('access_token');
    }

    // 创建请求头
    const headers = {
        'Content-Type': 'application/json'
    };

    // 如果token存在，添加到请求头
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
        console.log('已添加Authorization头:', headers['Authorization']);
    } else {
        console.warn('未找到有效的token');
    }

    fetch(`${API_URL}/documents/${encodeURIComponent(source)}`, {
        method: 'DELETE',
        credentials: 'include',
        headers: headers
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`API响应错误: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        // 移除加载状态
        document.body.removeChild(loadingElement);

        if (data.success) {
            // 显示删除成功提示
            const successElement = document.createElement('div');
            successElement.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
            successElement.innerHTML = `
                <div class="bg-white rounded-lg p-6 max-w-md w-full dark:bg-gray-800">
                    <div class="text-center">
                        <i class="fa fa-check-circle text-green-500 text-4xl mb-4"></i>
                        <p class="text-gray-700 dark:text-gray-300 mb-4">文档删除成功</p>
                        <button id="close-success" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
                            确定
                        </button>
                    </div>
                </div>
            `;
            document.body.appendChild(successElement);

            // 关闭按钮事件
            document.getElementById('close-success').addEventListener('click', function() {
                document.body.removeChild(successElement);
                // 重新加载文档列表
                loadDocuments();
            });
        } else {
            throw new Error('删除文档失败');
        }
    })
    .catch(error => {
        console.error('删除文档失败:', error);
        // 移除加载状态
        document.body.removeChild(loadingElement);

        // 显示删除失败提示
        const errorElement = document.createElement('div');
        errorElement.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        errorElement.innerHTML = `
            <div class="bg-white rounded-lg p-6 max-w-md w-full dark:bg-gray-800">
                <div class="text-center">
                    <i class="fa fa-times-circle text-red-500 text-4xl mb-4"></i>
                    <p class="text-gray-700 dark:text-gray-300 mb-4">删除文档失败: ${error.message}</p>
                    <button id="retry-delete" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
                        重试
                    </button>
                </div>
            </div>
        `;
        document.body.appendChild(errorElement);

        // 重试按钮事件
        document.getElementById('retry-delete').addEventListener('click', function() {
            document.body.removeChild(errorElement);
            deleteDocument(source);
        });
    });
}

// 页面加载完成后初始化知识库管理
document.addEventListener('DOMContentLoaded', function() {
    initKnowledgeBaseManagement();
});
